package com.hanlink.dsp.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.BounceInterpolator;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.SPUtils;
import com.edge.pbxdsp.R;
import com.hanlink.dsp.BtDspApplication;
import com.hanlink.dsp.DspContext;
import com.hanlink.dsp.DspSettings;

import com.hanlink.dsp.ca.model.channel.EqChannel;
import com.hanlink.dsp.ca.model.channel.LevelChannel;
import com.hanlink.dsp.ca.model.channel.SummingChannel;
import com.hanlink.dsp.ca.model.channel.XoverChannel;
import com.hanlink.dsp.ca.model.settings.AdvanceSettings;
import com.hanlink.dsp.ca.model.settings.EqSettings;
import com.hanlink.dsp.ca.model.settings.HomeSettings;
import com.hanlink.dsp.ca.model.settings.SummingSettings;
import com.hanlink.dsp.ca.model.settings.XoverSettings;
import com.hanlink.dsp.model.LocalStorage;
import com.hanlink.dsp.model.UserProfile;
import com.hanlink.dsp.ui.CaAmpDspActivity;
import com.hanlink.dsp.ui.dialog.ConfirmInputDialog;
import com.hanlink.dsp.util.DataUtil;
import com.hanlink.dsp.util.DialogHelper;
import com.hanlink.dsp.util.ToolUtil;
import com.hanlink.dsp.util.YzToast;
import com.qztech.sdk.ui.fragment.BaseFragment;
import com.qztech.sdk.ui.fragment.SaveFragmentCallback;
import com.qztech.sdk.ui.widget.SwipeMenuListView;
import com.qztech.utils.YzDebug;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.qztech.sdk.ui.fragment.BaseDrawerFragment.STATE_SELECTED_POSITION;

public class SaveDialogFragment extends BaseFragment {

    private List<UserProfile> dspSettingsList;
    private SettingAdapter mSettingAdapter;
    private DbManager db;
    protected SharedPreferences sp;
    private boolean isHorizontal;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        isHorizontal = getArguments().getBoolean("IS_HORIZONTAL", false);
    }


    @Override
    public void onViewCreated(@NonNull final View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mCallbacks = (CaAmpDspActivity) getActivity();
        View mTxtSaveBase = view.findViewById(R.id.txtSaveBase);
        View mTxtSaveAdvanced = view.findViewById(R.id.txtSaveAdvanced);
        SwipeMenuListView mDrawerListView = view.findViewById(R.id.lvItems);
        mDrawerListView.setOnItemClickListener((parent, view1, position, id) -> {
            final UserProfile userProfile = dspSettingsList.get(position);
            YzDebug.d("onViewCreated:" + userProfile.getId());
            if (userProfile.getMode() == 1) {
                String oldPassword = SPUtils.getInstance().getString(DspContext.KEY_PWD, DspContext.PASSOWRD);
                if (TextUtils.isEmpty(oldPassword)) {
                    showChangePasswordDialog(getActivity());
                    return;
                }
                showEnterPasswordDialog(getActivity(), v1 -> onItemSelected(view1, position, userProfile));
            } else {
                onItemSelected(view1, position, userProfile);
            }

        });
        mSettingAdapter = new SettingAdapter();
        db = BtDspApplication.getInstance().getDbManager();
        mDrawerListView.setAdapter(mSettingAdapter);

        // set creator
        mDrawerListView.setMenuCreator(ToolUtil.buildDeleteCreator(getActivity()));

        // step 2. listener item click event
        mDrawerListView.setOnMenuItemClickListener((position, menu, index) -> {
            if (index == 0) {// delete
                final UserProfile userProfile = dspSettingsList.get(position);
                if (userProfile.getMode() == 1) {
                    showEnterPasswordDialog(getActivity(), v1 -> delete(position));
                } else {
                    delete(position);
                }
            }
        });


        // set SwipeListener
        mDrawerListView.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {
            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end

            }
        });

        // other setting
        mDrawerListView.setCloseInterpolator(new BounceInterpolator());

        // test item long click
        mDrawerListView.setOnItemLongClickListener((parent, view12, position, id) -> false);

        mTxtSaveAdvanced.setOnClickListener(v -> {
            SPUtils spUtils = SPUtils.getInstance(Context.MODE_PRIVATE);
            String oldPassword = spUtils.getString(DspContext.KEY_PWD, DspContext.PASSOWRD);
            if (TextUtils.isEmpty(oldPassword)) {
                showChangePasswordDialog(getActivity());
            } else {
                showEnterPasswordDialog(getActivity(), v1 -> showSaveNewSettingsDialog(1));
            }

        });
        mTxtSaveBase.setOnClickListener(v -> showSaveNewSettingsDialog(0));

    }

    private void onItemSelected(View view, int position, UserProfile userProfile) {
        // DspSettings.updateUserProfile(userProfile); ;
        sp.edit().putInt(STATE_SELECTED_POSITION, position).apply();
        if (mCallbacks != null) {
            mCallbacks.onDrawerItemSelected(Gravity.START, view, position, dspSettingsList.get(position).getId());
        }
    }


    private void showEnterPasswordDialog(Context ctx, View.OnClickListener listener) {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(ctx, com.qztech.sdk.R.style.dialog);
        View view = LayoutInflater.from(ctx).inflate(R.layout.dialig_view_show_password, null, false);
        TextView tvCancel = view.findViewById(R.id.tvCancel);
        TextView tvOk = view.findViewById(R.id.tvOk);
        TextView tvChange = view.findViewById(R.id.tvChange);
        TextView etPassword = view.findViewById(R.id.etPassword);
        SPUtils spUtils = SPUtils.getInstance(Context.MODE_PRIVATE);
        String oldPassword = spUtils.getString(DspContext.KEY_PWD, DspContext.PASSOWRD);
        androidx.appcompat.app.AlertDialog alertDialog = builder.setView(view)

                .setCancelable(false)
                .create();
        tvCancel.setOnClickListener(v -> {
            alertDialog.dismiss();
        });
        tvOk.setOnClickListener(v -> {
            if (etPassword.getText() == null || etPassword.getText().length() == 0) {
                YzToast.showShort("Please enter password!");
                return;
            }

            if (oldPassword.equals(etPassword.getText().toString())) {
                if (listener != null) {
                    listener.onClick(v);
                }
                alertDialog.dismiss();
            } else {
                YzToast.showShort(com.hanlink.res.R.string.save_settings_password_error);

//                ToastUtils.showShort();
            }
        });
        tvChange.setOnClickListener(v -> {
            alertDialog.dismiss();
            showChangePasswordDialog(getActivity());
        });
        tvCancel.setOnClickListener(v -> alertDialog.dismiss());
        alertDialog.show();
    }

    private void showChangePasswordDialog(Context ctx) {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(ctx, com.qztech.sdk.R.style.dialog);
        View view = LayoutInflater.from(ctx).inflate(R.layout.dialig_view_change_password, null, false);
        EditText etOldPassword = view.findViewById(R.id.etOldPassword);
        TextView tvOldPasswordLabel = view.findViewById(R.id.tvOldPasswordLabel);
        EditText etNewPassword = view.findViewById(R.id.etNewPassword);
        EditText etNewPasswordAgain = view.findViewById(R.id.etNewPasswordAgain);
        TextView tvCancel = view.findViewById(R.id.tvCancel);
        TextView tvOk = view.findViewById(R.id.tvOk);
        SPUtils spUtils = SPUtils.getInstance(Context.MODE_PRIVATE);
        String oldPassword = spUtils.getString(DspContext.KEY_PWD, DspContext.PASSOWRD);
        if (TextUtils.isEmpty(oldPassword)) {
            ((TextView) view.findViewById(R.id.title)).setText(com.hanlink.res.R.string.title_set_password);
            etOldPassword.setVisibility(View.GONE);
            tvOldPasswordLabel.setVisibility(View.GONE);
        }
        androidx.appcompat.app.AlertDialog alertDialog = builder.setView(view)
//                .setTitle(R.string.title_change_password)
                .setCancelable(false)
                .create();
        tvCancel.setOnClickListener(v -> {
            alertDialog.dismiss();
        });
        tvOk.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(oldPassword) && (etOldPassword.getText() == null || etOldPassword.getText().length() == 0)) {
                YzToast.showShort("Please enter old password!");
//                Toast.makeText(ctx, , Toast.LENGTH_SHORT).show();
                return;
            }
            if (!TextUtils.isEmpty(oldPassword) && !oldPassword.equals(etOldPassword.getText().toString())) {
                YzToast.showShort(com.hanlink.res.R.string.save_settings_password_error);
//                Toast.makeText(ctx,, Toast.LENGTH_SHORT).show();
                return;
            }
            if (etNewPassword.getText() == null || etNewPassword.getText().length() == 0) {
                YzToast.showShort("Please enter new password!");
//                Toast.makeText(ctx, "Please enter new password!", Toast.LENGTH_SHORT).show();
                return;
            }
            if (etNewPasswordAgain.getText() == null || etNewPasswordAgain.getText().length() == 0) {
                YzToast.showShort("Please enter new password again!");
//                Toast.makeText(ctx, "Please enter new password again!", Toast.LENGTH_SHORT).show();
                return;
            }
            if (etNewPassword.getText().toString().equals(etNewPasswordAgain.getText().toString())) {
                spUtils.put(DspContext.KEY_PWD, etNewPassword.getText().toString().trim());
                YzToast.showShort("Password changed!");
//                Toast.makeText(ctx, "Password changed!", Toast.LENGTH_SHORT).show();
                alertDialog.dismiss();
            } else {
                YzToast.showShort("Please enter same password!");
//                Toast.makeText(ctx, "Please enter same password!", Toast.LENGTH_SHORT).show();
            }

        });
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.show();

    }


    private void showSaveNewSettingsDialog(final int mode) {
        final ConfirmInputDialog dialog = new ConfirmInputDialog(getContext());
        dialog.getEditText().setInputType(InputType.TYPE_CLASS_TEXT);
        dialog.setOnOkListener((dialog1, text) -> {
            dialog1.dismiss();
            saveAsNewSettings(text, mode);
        });
        dialog.show();


    }

    /**
     * 保存配置
     */
    protected void saveAsNewSettings(String name, int mode) {
        try {
            if ("".equals(name)) {
                YzToast.showShort(com.hanlink.res.R.string.name_empty);
//                Toast.makeText(getActivity(), , Toast.LENGTH_SHORT).show();
                return;
            }

            UserProfile userProfile = new UserProfile(name);
            userProfile.setDev(DspContext.getDevType().ordinal());
            userProfile.setMode(mode);
            db.saveOrUpdate(userProfile);
            DataUtil.saveEqToDb(userProfile.getId(),db,
                    DspSettings.HOME_SETTINGS,
                    DspSettings.SUMMING_SETTINGS,
                    DspSettings.EQ_SETTINGS,
                    DspSettings.XOVER_SETTINGS,
                    DspSettings.ADVANCE_SETTINGS
                    );

            if (mCallbacks != null) {
                mCallbacks.onDrawerItemAdded(Gravity.LEFT, null, 0, 0);
            }
            reloadSettings();
        } catch (DbException e) {
            e.printStackTrace();
            YzDebug.d("saveAsNewSettings",e);
            YzToast.showShort(com.hanlink.res.R.string.db_name_not_unique);
//            Toast.makeText(getActivity(), R.string.db_name_not_unique, Toast.LENGTH_SHORT).show();
        }
    }

    public void reloadSettings() {
        try {

            List<UserProfile> list = db.selector(UserProfile.class)
                    .orderBy("id")
                    .limit(50).findAll();
            List<UserProfile> tmp = new ArrayList<>();
            if (list != null) {
                int devType = DspContext.getDevType().ordinal();
                for (UserProfile profile : list) {
                    if (DspSettings.DEFAULT_USERP_PROFILE.getName().equals(profile.getName()))
                        continue;
                    if (profile.getDev() == 0 || profile.getDev() == devType) {
                        tmp.add(profile);
                    }
                }
            }
            dspSettingsList = tmp;
        } catch (Exception e) {
            e.printStackTrace();
        }
        mSettingAdapter.notifyDataSetChanged();
    }

    private void delete(final int position) {
        DialogHelper.confirm(getActivity(), com.hanlink.res.R.string.title_save_delete_confirm, com.hanlink.res.R.string.save_message_delete,
                com.hanlink.res.R.string.ok, com.hanlink.res.R.string.cancel, (dialog, which) -> {
                    new LocalStorage().deleteSettings(getActivity().getApplicationContext(), db, dspSettingsList.get(position).getId());

                    if (mCallbacks != null) {
                        mCallbacks.onDrawerItemDeleted(Gravity.LEFT, null, dspSettingsList.get(position).getId(), 0);
                    }
                    dspSettingsList.remove(position);
                    mSettingAdapter.notifyDataSetChanged();
                    int newPosition = position - 1;
                    if (newPosition < 0) {
                        newPosition = 0;
                    }
                    //mDrawerListView.setItemChecked(newPosition, true);
                    dialog.cancel();
                });
    }

    @Override
    public void onPause() {
        super.onPause();
    }


    @Override
    public void onRefreshFragment(int cmd) {

    }

    @Override
    public void onResume() {
        super.onResume();
        reloadSettings();
    }

    @Override
    protected int getResourceId() {
        return R.layout.fragment_drawer_save;

    }

    class SettingAdapter extends BaseAdapter {
        private final String DATE_FORMAT = "yyyy-MM-dd    HH:mm:ss";
        private final SimpleDateFormat mDateFormat;

        @SuppressLint("SimpleDateFormat")
        SettingAdapter() {
            mDateFormat = new SimpleDateFormat(DATE_FORMAT);
        }

        @Override
        public int getCount() {
            return dspSettingsList == null ? 0 : dspSettingsList.size();
        }

        @Override
        public UserProfile getItem(int position) {
            return dspSettingsList == null || dspSettingsList.size() == 0 ? null : dspSettingsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return dspSettingsList == null || dspSettingsList.size() == 0 ? -1 : dspSettingsList.get(position).getId();
        }

        @SuppressLint("CheckResult")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(getActivity(),
                        com.hanlink.res.R.layout.save_drawer_item, null);
                holder = new ViewHolder(convertView);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            UserProfile item = getItem(position);
            YzDebug.d("getView   item pos:" + position + " id:" + item.getId());
            holder.tv_name.setText(item.getName());
            holder.tv_time.setText(mDateFormat.format(item.getCreateDate()));
            holder.tv_name.setTag(holder);
            if (item.getMode() == 1) {
                holder.iv_image.setVisibility(View.VISIBLE);
            } else {
                holder.iv_image.setVisibility(View.INVISIBLE);
            }
            holder.id = item.getId();
            holder.btn_send.setOnClickListener(v -> {
                if (getActivity() != null) {
                    ((CaAmpDspActivity) getActivity()).showLoadingDialog("Loading", false);
                }
                Observable.create((ObservableOnSubscribe<File>) emitter -> {
                    final String name = BtDspApplication.getInstance().getString(R.string.app_name);
                    File file = new File(BtDspApplication.getInstance().getExternalCacheDir(), name +/*"_" + item.getName() + */".SP8");
                    if (file.exists()) {
                        file.delete();
                    }
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        emitter.onError(e);
                        return;
                    }
                    if (!DataUtil.saveDspToShareFile(file, item)) {
                        emitter.onError(new IOException("save error"));
                        return;
                    }
                    emitter.onNext(file);
                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(file -> {
                            if (getActivity() != null) {
                                ((CaAmpDspActivity) getActivity()).dismissLoading();
                            }
                            Uri fileUri = FileProvider.getUriForFile(
                                    BtDspApplication.getInstance(),
                                    BtDspApplication.getInstance().getPackageName() + ".fileprovider",
                                    file);
                            Intent intent = new Intent(Intent.ACTION_SEND);
                            intent.setData(Uri.parse("mailto:"));
                            intent.putExtra(Intent.EXTRA_EMAIL, "");
                            intent.setType("text/plain");
                            intent.putExtra(Intent.EXTRA_STREAM, fileUri);
                            startActivity(Intent.createChooser(intent, BtDspApplication.getInstance().getString(R.string.app_name)));
                        }, e -> {
                            if (getActivity() != null) {
                                ((CaAmpDspActivity) getActivity()).dismissLoading();
                            }
                            e.printStackTrace();
                            YzToast.showShort("Share file error!");
//                            Toast.makeText(getActivity(), "Share file error!", Toast.LENGTH_SHORT).show();
                        });
            });
            return convertView;
        }

        class ViewHolder {

            int id;
            TextView tv_name;
            TextView tv_time;
            ImageView iv_image;
            ImageButton btn_send;

            public ViewHolder(View view) {
                tv_name = view.findViewById(android.R.id.text1);
                tv_time = view.findViewById(android.R.id.text2);
                iv_image = view.findViewById(com.hanlink.res.R.id.img);
                btn_send = view.findViewById(com.hanlink.res.R.id.btn_send_email);
                view.setTag(this);
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    protected SaveFragmentCallback mCallbacks;

    public void setCallbacks(SaveFragmentCallback callbacks) {
        this.mCallbacks = callbacks;
    }

}
